﻿using System;
using System.Data;
using Pantry.Business;
using Pantry.Entity;
using Pantry.Commons;

namespace Pantry.Web.Users.Controls
{
    public partial class DepartmentDetail : System.Web.UI.UserControl
    {
        private DepartmentBus _departmentBus;
        protected void Page_Load(object sender, EventArgs e)
        {
            ListTypeOfBusiness.SendvaluesToThePage += delegate(string message)
            {
                string[] str = message.Split('$');
                TextBoxTypeOfBusiness.Text = str[0];
                TextBoxSicCode.Text = str[1];
                HiddenFieldTypeOfBusinessId.Value = str[2];
            };
            ListContact.SendContactToPage += delegate(string contact)
            {
                string[] contacts = contact.Split('$');
                HiddenFieldContactId.Value = contacts[0];
                TextBoxLeadContact.Text = contacts[1];
            };
            ListPostcode.sendPostcodeToPage += delegate(string values)
            {
                string[] postcodeValues = values.Split('$');
                TextBoxPostcode.Text = postcodeValues[0];
                TextBoxTown.Text = postcodeValues[1];
                TextBoxCounty.Text = postcodeValues[2];
                DropDownListNational.SelectedValue = postcodeValues[3];
            };
            if(!IsPostBack)
            {
                if (Request.QueryString["action"] == "create")
                {
                    LoadCountryToDropDownList();
                }
                else if(Request.QueryString["action"] == "update" && Request.QueryString["id"] != null)
                {
                    try
                    {
                        LoadCountryToDropDownList();
                        var departmentId = int.Parse(Request.QueryString["id"]);
                        LoadEditData(departmentId);
                    }
                    catch (FormatException ex)
                    {
                        ExceptionHandler.WriteErrorLog(ex);
                    }
                }
                else if(Request.RawUrl == "ViewListTeam.aspx" && Request.QueryString["id"] != null)
                {
                    try
                    {
                        LoadCountryToDropDownList();
                        int departmentId = int.Parse(Request.QueryString["id"]);
                        LoadEditData(departmentId);
                    }
                    catch (FormatException ex)
                    {
                        ExceptionHandler.WriteErrorLog(ex);
                    }
                }
            }
            if (Request.QueryString["id"] == null)
            {
                ButtonInActive.Visible = false;
            }
        }
        protected void LoadCountryToDropDownList()
        {
            var countryBus = new CountryBus();
            DataTable countries = countryBus.SelectAllCountry();
            DropDownListNational.DataTextField = "CountryName";
            DropDownListNational.DataValueField = "CountryId";
            DropDownListNational.DataSource = countries;
            DropDownListNational.DataBind();
        }
        protected void LoadEditData(int departmentId)
        {
            try
            {
                _departmentBus = new DepartmentBus();
                DataTable departmentById = _departmentBus.GetDepartmentById(departmentId);
                if (departmentById.Rows.Count > 0)
                {
                    TextBoxName.Text = departmentById.Rows[0]["DepartmentName"].ToString();
                    HiddenFieldName.Value = departmentById.Rows[0]["DepartmentName"].ToString();
                    TextBoxDescription.Text = departmentById.Rows[0]["ShortDescription"].ToString();
                    TextBoxLeadContact.Text = departmentById.Rows[0]["ContactName"].ToString();
                    HiddenFieldContactId.Value = departmentById.Rows[0]["ContactId"].ToString();
                    TextBoxAddress1.Text = departmentById.Rows[0]["AddressLine1"].ToString();
                    TextBoxAddress2.Text = departmentById.Rows[0]["AddressLine2"].ToString();
                    TextBoxAddress3.Text = departmentById.Rows[0]["AddressLine3"].ToString();
                    TextBoxPostcode.Text = departmentById.Rows[0]["Postcode"].ToString();
                    TextBoxTown.Text = departmentById.Rows[0]["Town"].ToString();
                    TextBoxCounty.Text = departmentById.Rows[0]["County"].ToString();
                    DropDownListNational.SelectedValue = departmentById.Rows[0]["Country"].ToString();
                    TextBoxTypeOfBusiness.Text = departmentById.Rows[0]["TypeOfBusinessName"].ToString();
                    HiddenFieldTypeOfBusinessId.Value = departmentById.Rows[0]["TypeOfBusinessId"].ToString();
                    TextBoxSicCode.Text = departmentById.Rows[0]["SicCode"].ToString();
                    TextBoxFullDescription.Text = departmentById.Rows[0]["FullDescription"].ToString();
                    TextBoxPhoneNumber.Text = departmentById.Rows[0]["PhoneNumber"].ToString();
                    TextBoxFax.Text = departmentById.Rows[0]["Fax"].ToString();
                    TextBoxEmail.Text = departmentById.Rows[0]["Email"].ToString();
                    TextBoxWebAddress.Text = departmentById.Rows[0]["WebAddress"].ToString();
                    ButtonInActive.Visible = bool.Parse(departmentById.Rows[0]["IsActivated"].ToString());
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
                Response.Write(ex.Message);
            }
        }
        protected void ButtonSaveClick(object sender, EventArgs e)
        {
            try
            {
                _departmentBus = new DepartmentBus();
                bool isExists = _departmentBus.CheckDepartmentNameExists(TextBoxName.Text.Trim());
                //if (!_departmentBus.CheckDepartmentNameExists(TextBoxName.Text))
                //{
                    int directorateId = 0;
                    if (Request.QueryString["directorateid"] != null && Request.QueryString["action"] == "create")
                    {
                        directorateId = int.Parse(Request.QueryString["directorateid"]);
                    }
                    var department = new Department
                                         {
                        DirectorateId = directorateId,
                        DepartmentName = TextBoxName.Text,
                        ShortDescription = TextBoxDescription.Text,
                        ContactId = int.Parse(HiddenFieldContactId.Value),
                        AddressLine1 = TextBoxAddress1.Text,
                        AddressLine2 = TextBoxAddress2.Text,
                        AddressLine3 = TextBoxAddress3.Text,
                        Postcode = TextBoxPostcode.Text,
                        Town = TextBoxTown.Text,
                        County = TextBoxCounty.Text,
                        Country = int.Parse(DropDownListNational.SelectedValue),
                        TypeOfBusinessId = int.Parse(HiddenFieldTypeOfBusinessId.Value),
                        SicCode = TextBoxSicCode.Text,
                        FullDescription = TextBoxFullDescription.Text,
                        PhoneNumber = TextBoxPhoneNumber.Text,
                        Fax = TextBoxFax.Text,
                        Email = TextBoxEmail.Text,
                        WebAddress = TextBoxWebAddress.Text,
                        IsActivated = true
                    };

                    if (Request.QueryString["action"] == "update" && Request.QueryString["id"] != null)
                    {
                        int departmentId = int.Parse(Request.QueryString["id"]);
                        //DataTable departmentById = _departmentBus.GetDepartmentById(departmentId);
                        string departmentName = HiddenFieldName.Value;
                        if (departmentName != TextBoxName.Text)
                        {
                            if (!isExists)
                            {
                                department.DepartmentId = departmentId;
                                bool result = _departmentBus.UpdateDepartment(department);
                                Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                        result
                                                                            ? "showmessage('Update department successfully !','SUCCESS','','false');"
                                                                            : "showmessage('Update department failed !','ERROR','','false');",
                                                                        true);
                                //Response.Redirect(Request.RawUrl + "#table_wTabs-2");
                            }
                            else
                            {
                                TextBoxName.Focus();
                                Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                        "showmessage('Department Name is already exists !','ERROR','','false');",
                                                                        true);

                            }
                            
                        }
                        else
                        {
                            department.DepartmentId = departmentId;
                            bool result = _departmentBus.UpdateDepartment(department);
                            Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                    result
                                                                        ? "showmessage('Update department successfully !','SUCCESS','','false');"
                                                                        : "showmessage('Update department failed !','ERROR','','false');",
                                                                    true);
                        }
                    }
                        

                    
                    else
                    {
                        if (!isExists)
                        {
                            bool result = _departmentBus.AddDepartment(department);
                            Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                    result
                                                                        ? "showmessage('Create new department successfully !','SUCCESS','','false');"
                                                                        : "showmessage('Cannot create new department !','ERROR','','false');",
                                                                    true);
                        }
                        else
                        {
                            TextBoxName.Focus();
                            Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                    "showmessage('Department Name is already exists !','ERROR','','false');",
                                                                    true);

                        }
                    }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        protected void ButtonBackClick(object sender, EventArgs e)
        {
            Response.Redirect("DirectorateDetails.aspx?id="+Request.QueryString["directorateid"]+"&mode=edit#table_wTabs-2");
        }
        protected void ButtonInActiveClick(object sender, EventArgs e)
        {
            int derpartmentId = int.Parse(Request.QueryString["id"]);
            _departmentBus = new DepartmentBus();
            bool result = _departmentBus.MarkActivated(derpartmentId, false);
            if(result)
            {
                Response.Redirect("DirectorateDetails.aspx?id=" + Request.QueryString["directorateid"] + "&mode=edit#table_wTabs-2");
            }
        }
        protected void RadioButtonOrganizationCheckedChanged(object sender, EventArgs e)
        {
            int directorateId = int.Parse(Request.QueryString["directorateid"]);
            Directorate directorate = new DirectorateBus().GetDirectorateById(directorateId);
            
            if(RadioButtoParent.Checked)
            {
                TextBoxAddress1.Text = directorate.AddressLine1;
                TextBoxAddress2.Text = directorate.AddressLine2;
                TextBoxAddress3.Text = directorate.AddressLine3;
            }
            else if (RadioButtonOrganization.Checked)
            {
                var organizationId = directorate.OrganizationId;
                var organization = new OrganizationBus().ReturnOrganizationById(organizationId);
                TextBoxAddress1.Text = organization.Address1;
                TextBoxAddress2.Text = organization.Address2;
                TextBoxAddress3.Text = organization.Address3;
            }
        }   
    }
}